﻿package net.wangit.framework.expression;

import net.wangit.Path;
import net.wangit.util.Checker;
import net.wangit.util.DateUtil;
import net.wangit.util.StringUtil;
/**
 * 常量表达式
 * @author watson
 *
 */
public class ConstantExpression {

	private static final String PREFIX = "$C{";
	private static final String SUFFIX = "}";
	private static final String ROOT = "root";
	private static final String HOME = "home";
	private static final String DATE = "date";
	private static final String TIME = "time";
	private static final String DATETIME = "datetime";

	public ConstantExpression() {
	}

	public static final String resolve(String expression) {
		if (Checker.isEmpty(expression))
			return expression;
		StringBuffer result = new StringBuffer();
		String attribute;
		while ((attribute = StringUtil.find(expression,
				ConstantExpression.PREFIX, ConstantExpression.SUFFIX)) != null) {
			int index = expression.indexOf((new StringBuilder(
					ConstantExpression.PREFIX)).append(attribute).append(
					ConstantExpression.SUFFIX).toString());
			result.append(expression.substring(0, index)).append(
					getValue(attribute));
			expression = expression.substring(index + attribute.length()
					+ ConstantExpression.PREFIX.length()
					+ ConstantExpression.SUFFIX.length());
		}
		result.append(expression);
		return result.toString();
	}

	private static String getValue(String attribute) {
		if (ConstantExpression.ROOT.equals(attribute))
			return Path.getRootPath();
		if (ConstantExpression.HOME.equals(attribute))
			return Path.getHomePath();
		if (ConstantExpression.DATE.equals(attribute))
			return DateUtil.getCurrentDate();
		if (ConstantExpression.TIME.equals(attribute))
			return DateUtil.getCurrentTime();
		if (ConstantExpression.DATETIME.equals(attribute))
			return DateUtil.getCurrentDatetime();
		else
			throw new UnsupportedOperationException((new StringBuilder(
					"Unsupported attribute: ")).append(attribute).toString());
	}
}
